package export

import (
	"encoding/csv"
	"fmt"
	"game/game-design-v.xnanz/loader"
	"io"
	"os"
	"strings"
)

type CsvIO struct {
}

// 读取csv文件
func (c *CsvIO) Read(fileFullName string) ([]*loader.DesignFile, error) {
	var designFiles []*loader.DesignFile = make([]*loader.DesignFile, 0)
	file0, err := os.Open(fileFullName)
	if err != nil {
		fmt.Println("Read1", err)
		return designFiles, err
	}
	reader := csv.NewReader(file0)

	rows := make([][]string, 0) //.ReadAll()
	var unfinish bool = true
	for unfinish {
		oneRow, err := reader.Read()
		if err != nil && err == io.EOF {
			unfinish = false
			break
		}
		rows = append(rows, oneRow)
	}

	if err != nil {
		return designFiles, err
	}
	fileInfo, err := os.Stat(fileFullName)
	if err != nil {
		return designFiles, err
	}

	dFile := loader.NewDesignFile(fileInfo.Name(), rows)
	designFiles = append(designFiles, dFile)
	return designFiles, nil
}

func (c *CsvIO) Write(designFile *loader.DesignFile, exportFor *ExportFor) {
	os.Mkdir(exportFor.OutputFolder, 0755)
	if !designFile.FileNeedExport(exportFor.Tags) {
		fmt.Println(exportFor.Tags, "导出忽略\t", designFile.Name)
		return
	}

	file, err := os.OpenFile(fmt.Sprintf("%s%s.csv", exportFor.OutputFolder, designFile.GetOutputName()), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
	if err != nil {
		fmt.Println(exportFor.Tags, "导出异常\t", designFile.Name)
		return
	}
	defer file.Close()

	writer := csv.NewWriter(file)

	names := make([]string, 0, len(designFile.Fields))
	types := make([]string, 0, len(designFile.Fields))
	tags := make([]string, 0, len(designFile.Fields))
	comments := make([]string, 0, len(designFile.Fields))

	names = append(names, "#name")
	types = append(types, "#type")
	tags = append(tags, "#tag")
	comments = append(comments, "#comment")

	for i, field := range designFile.Fields {
		if i > 0 {
			needExport := loader.FieldNeedExport(field.FieldTags, exportFor.Tags)
			if !needExport {
				continue
			}
		}
		names = append(names, field.FieldName)
		types = append(types, field.FieldType)
		tags = append(tags, strings.Join(field.FieldTags, ","))
		comments = append(comments, field.FieldComment)
	}

	marcos := make([]string, 0)
	marcos = append(marcos, designFile.Macros...)

	fieldLines := make([][]string, 5)
	fieldLines[0] = marcos
	fieldLines[designFile.NameRow] = names
	fieldLines[designFile.TypeRow] = types
	fieldLines[designFile.TagRow] = tags
	fieldLines[designFile.CommentRow] = comments

	for _, line := range fieldLines {
		writer.Write(line)
	}

	for _, data := range designFile.Datas {
		var rowDatas []string
		rowDatas = append(rowDatas, "")
		for i, field := range designFile.Fields {
			needExport := loader.FieldNeedExport(field.FieldTags, exportFor.Tags)
			if !needExport {
				continue
			}
			if i >= len(data) {
				rowDatas = append(rowDatas, "")
			} else {
				rowDatas = append(rowDatas, data[i])
			}
		}
		writer.Write(rowDatas)
	}
	writer.Flush()
	fmt.Println("导出成功", designFile.Name)
}
